<?php
	
	require_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."core".DIRECTORY_SEPARATOR."functions.php");
	require_once("Database.php");
	
	class Person extends dbConn
	{
		private $personId;
		private $firstName,$lastName;
		private $password;
		private $email;
		private $contactNumber,$gender,$accountType,$dateCreated,$activated;
		private $salt;
		private $activationKey;

		//optional fields
		private $universityId,$degreeName,$yearOfDegree;
		private $majors,$driversLicence,$highSchool,$entryToUTS,$previousInternships;
		private $extraCurricularActivities,$scholarships,$paperworkStatus,$internshipOrganised;
		private $workshops,$skills,$refugee,$indigeneous,$address,$contractExpiration,$offer;

		private $db;

		public function __construct($personId)
		{
			$this->db = new dbConn();
			$this->personId = $personId;
			$this->fetchData();
		}

		private function fetchData()
		{
			$res = $this->db->query("SELECT * FROM person WHERE ".P_ID."='$this->personId'");
			if($this->db->num_rows($res) != 1)
			{
				die("FATAL ERROR : User.php Cannot Fetch Data for id : ".$this->id);
			}
			else
			{
				$data = $this->db->fetch_array($res);
				$this->activated = $data["activated"];
				//if($data["activated"] == 0)
				//{
				//	die("Account Not activated");
				//}
				//else
				//{
					$this->email = $data[P_E]; 
					$this->activationKey = $data[P_AK];
					$this->firstName = $data[P_FN];
					$this->lastName = $data[P_LN];
					$this->password = $data[P_P];
					$this->contactNumber = $data[P_CN];
					$this->gender = $data[P_G];
					$this->accountType = $data[P_AT];
					$this->dateCreated = $data[P_DC];
					$this->activated = $data[P_ACT];
					$this->salt = $data[P_S];
					$this->universityId = $data[P_UI];
					$this->degreeName = $data[P_DN];
					$this->majors = $data[P_MAJ];
					$this->driversLicence = $data[P_DL];
					$this->highSchool = $data[P_HS];
					$this->entryToUTS = $data[P_EUTS];
					$this->previousInternships = $data[P_PIS];
					$this->extraCurricularActivities = $data[P_ECA];
					$this->scholarships = $data[P_SCH];
					$this->paperworkStatus = $data[P_PWS];
					$this->internshipOrganised = $data[P_IO];
					$this->workshops = $data[P_WKS];
					$this->skills = $data[P_SKS];
					$this->refugee = $data[P_RFG];
					$this->indigeneous = $data[P_IND];
					$this->address = $data[P_ADD];
					$this->contractExpiration = $data[P_CONE];
					$this->offer = $data[P_OFF];
					$this->yearOfDegree = $data[P_YOD];
				//}
				
			}
		}

		public function update($fieldName,$value,$isInt = false)
		{
			if($isInt)
			{
				$this->query("UPDATE person SET $fieldName=$value WHERE personId=$this->personId");
			}
			else
			{
				$this->query("UPDATE person SET $fieldName='$value' WHERE personId=$this->personId");
			}
			
		}


		/**
			GETTERS AND SETTERS FUNCTIONS
		 */

		//universal getter function
		public function __get($var)
		{
			if(isset($this->$var))
			{
				return $this->$var;
			}
			else
			{
				return "NULL";
			}
		}

		public static function getPersonsByType($type1,$type2=null,$type3=null)
		{
			$cdb = new dbConn();

			$cnd = "accountType='$type1'";

			if($type2!=null && $type3==null)
			{
				$cnd = "accountType='$type1' OR accountType='$type2'";
			}
			else if($type3!=null)
			{
				$cnd = "accountType='$type1' OR accountType='$type2' OR accountType='$type3'";
			}

			$query = "SELECT personId,firstName,lastName FROM person WHERE ".$cnd;

			$res = $cdb->query($query);
			if($cdb->num_rows($res) >= 1)
			{
				$array = array();
				while($row = $cdb->fetch_array($res))
				{
					$array[] = $row;
				}
				return ($array);
			}
			else
			{
				return null;
			}
		}

		public function isAdmin()
		{
			if($this->accountType==ACC_ADMIN)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		public function isEvtMgr()
		{
			if($this->accountType == ACC_EVTMGR)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		public function setEmail($newVal)
		{
			$this->update(P_E,$newVal);
		}

		public function setFirstName($firstName)
		{
			$this->update(P_FN,$firstName);
		}

		public function setLastName($lastName)
		{
			$this->update(P_LN,$lastName);
		}

		public function setContact($contactNumber)
		{
			$this->update(P_CN,$contactNumber);
		}
		
		public function setActivated($activated)
		{
			$this->update(P_ACT,$activated,true);
		}

		public function setAccountType($accountType)
		{
			if(!constant($accountType))
			{
				die("Please supply a correct account Type!!");
			}
			else
			{
				$this->accountType = $accountType;
			}
		}

		public function setPassword($password)
		{
			$this->update(P_P,$password);
		}

		public function setUniversityId($universityId)
		{
			$this->update(P_UI,$universityId,true);
		}

		public function setActivationKey($activationKey)
		{
			$this->update(P_ACT,$activationKey);
		}

		public function updateProfile($firstName,$lastName,$accountType,$email,$skills,$gender,$contactNumber,$address,$activated)
		{
			$activationKey = md5($firstName.$lastName.$email);
			$this->query("UPDATE person SET ".P_FN."='$firstName',".P_LN."='$lastName',".P_AT."='$accountType',".P_E."='$email',".P_SKS."='$skills',".P_G."='$gender',".P_CN."='$contactNumber',".P_ADD."='$address',".P_AK."='$activationKey',".P_ACT."='$activated' WHERE ".P_ID."=".$this->personId);
			$this->fetchData();
		}
        
        public function updateStaffId($staffId)
        {
            $this->query("UPDATE person SET ".P_UI."='$staffId' WHERE ".P_ID."=".$this->personId);
            $this->fetchData();
        }

		public function updateUniversityDetails($universityId,$degreeName,$majors,$yod,$entryToUts,$highSchool,$eca,$scholarShips,$previousInternships,$internshipOrganised)
		{
			$this->query("UPDATE person SET ".P_UI."=$universityId,".P_DN."='$degreeName',".P_MAJ."='$majors',".P_YOD."='$yod',".P_EUTS."='$entryToUts',".P_HS."='$highSchool',".P_ECA."='$eca',".P_SCH."='$scholarShips',".P_PIS."='$previousInternships',".P_IO."=$internshipOrganised WHERE ".P_ID."=".$this->personId);
			$this->fetchData();
		}

		public function	updateOtherDetails($availaibity,$workshops,$driversLicence,$refugee,$indigenous,$paperwork,$contract,$offer)
		{
			$this->query("UPDATE person SET ".P_AVL."='$availaibity',".P_WKS."='$workshops',".P_RFG."=$refugee,driversLicence=$driversLicence,".P_IND."=$indigenous,".P_PWS."='$paperwork',".P_CONE."='$contract',".P_OFF."=$offer WHERE ".P_ID."=$this->personId");
		}
        
        public function	updateEditProfileOtherDetails($availaibity,$workshops,$driversLicence,$refugee,$indigenous)
		{
			$this->query("UPDATE person SET ".P_AVL."='$availaibity',".P_WKS."='$workshops',".P_RFG."=$refugee,driversLicence=$driversLicence,".P_IND."=$indigenous WHERE ".P_ID."=$this->personId");
		}

		public static function getAllPersonIdName()
		{
			$db = new dbConn();
			$query = "SELECT personId,firstName,lastName FROM person";
			$res = $db->query($query);
			if($db->num_rows($res) >= 1)
			{
				$array = array();
				while($row = $db->fetch_array($res))
				{
					$array[] = $row;
				}
				return ($array);
			}
			else
			{
				return null;
			}
		}
        
        public static function getAppliedByPerson($id)
		{
			$db = new dbConn();
			$query = "SELECT applied.hoursWorked,applied.attended,role.title,role "
                . "FROM applied JOIN role ON applied.role=role.roleId "
                . "WHERE applied.person = $id AND applied.accepted = 'accepted' LIMIT 5";
			$res = $db->query($query);
			if($db->num_rows($res) >= 1)
			{
				$array = array();
				while($row = $db->fetch_array($res))
				{
					$array[] = $row;
				}
				return ($array);
			}
			else
			{
				return null;
			}
		}

		public static function getPersonNameById($id)
		{
			$db = new dbConn();
			$query = "SELECT firstName,lastName FROM person WHERE personId=$id";
			$res = $db->query($query);
			$data = $db->fetch_array($res);
			return $data["firstName"]." ".$data["lastName"];
		}
        
        public static function getPerson($id)
		{
			$db = new dbConn();
			$query = "SELECT * FROM person WHERE personId=$id";
			$res = $db->query($query);
			$data = $db->fetch_array($res);
			return $data;
		}

		public static function resetPassword($personId,$password)
		{
			$db = new dbConn();
			$res = $db->query("SELECT email,salt FROM person WHERE personId=$personId");
			$data = $db->fetch_array($res);
			$newPasswordHash = md5($password.$data["salt"]);
			if($db->insert("UPDATE person SET password='$newPasswordHash' WHERE personId=$personId"))
			{
				return true;
			}
			else
			{
				return false;
			}
        }
		

		public static function delete($personId)
		{
			$db = new dbConn();
			$res = $db->query("SELECT person "
                . "FROM manages JOIN event ON manages.event=event.eventId "
                . "WHERE manages.person=$personId AND "
                . "event.startDate<CURDATE() "
                . "AND event.endDate>CURDATE()");
			if($db->num_rows($res) > 0)
			{
				return "Cannot delete, manages an active event";
			}
			$res = $db->query("SELECT * "
                . "FROM applied JOIN role ON applied.role=role.roleId "
                . "WHERE applied.person=$personId "
                . "AND role.startDate<CURDATE() "
                . "AND role.endDate>CURDATE() "
                . "AND applied.accepted='accepted'");
            if($db->num_rows($res) > 0)
			{
				return "Canot delete, has active applicaitons";
			}
            $db->query("DELETE FROM applied WHERE person=$personId");
            $db->query("DELETE FROM manages WHERE person=$personId");
            $db->query("DELETE FROM person WHERE personId=$personId");
            return "true";
		}
        
        public static function generateReport($person)
        {
            $db = new dbConn();
            $query = "SELECT applied.hoursWorked,applied.accepted,applied.attended,applied.dateCreated,"
                ."role.roleId,role.description,role.title as role,"
                ."activity.activityId,activity.title as activity, "
                ."event.eventId,event.name as event,CONCAT(event.startDate,' to ',event.endDate) as eventDate "
                ."FROM applied JOIN role ON applied.role=role.roleId "
                ."             JOIN activity ON role.activity=activity.activityId "
                ."             JOIN event ON activity.event=event.eventId "
                ."WHERE applied.person=$person";
            $res = $db->query($query);
			if($db->num_rows($res) >= 1)
			{
				$array = array();
				while($row = $db->fetch_array($res))
				{
					$array[] = $row;
				}
				return ($array);
			}
			else
			{
				return null;
			}
        }
	}


?>